package com.zxjbyte.yiyi.framework.oss.config;

import com.zxjbyte.yiyi.framework.oss.client.FileClient;
import com.zxjbyte.yiyi.framework.oss.client.MasterFileClient;
import com.zxjbyte.yiyi.framework.oss.factory.DefaultOssConfigFactory;
import com.zxjbyte.yiyi.framework.oss.factory.OssConfigFactory;
import com.zxjbyte.yiyi.framework.oss.event.OssRecordListener;
import com.zxjbyte.yiyi.framework.oss.rule.OssRule;
import com.zxjbyte.yiyi.framework.oss.rule.OssRuleImpl;
import com.zxjbyte.yiyi.framework.oss.storage.db.DbOssTemplate;
import com.zxjbyte.yiyi.framework.oss.storage.local.LocalOssTemplate;
import com.zxjbyte.yiyi.framework.oss.storage.s3.S3OssTemplate;
import com.zxjbyte.yiyi.framework.redis.manager.RedisDao;
import com.zxjbyte.yiyi.module.system.api.oss.OssConfigApi;
import com.zxjbyte.yiyi.module.system.api.oss.OssFileApi;
import com.zxjbyte.yiyi.module.system.api.oss.OssRecordApi;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

/**
 * oss AutoConfiguration
 *
 * @Author zhangxingjia
 * @Date 2023/5/9 11:07
 * @Version: 1.0
 */
@RequiredArgsConstructor
@AutoConfiguration
@ConditionalOnProperty(prefix = OssProperties.OSS_PROP_PREFIX, value = "enabled", matchIfMissing = true)
@EnableConfigurationProperties(OssProperties.class)
public class YiyiOssAutoConfiguration {

    private final OssProperties properties;


    @Bean
    public OssConfigFactory ossConfigFactory(OssConfigApi ossConfigApi, RedisDao redisDao){
        return new DefaultOssConfigFactory(properties, ossConfigApi, redisDao);
    }

    @Bean
    @ConditionalOnMissingBean(OssRule.class)
    public OssRule ossRule() {
        return new OssRuleImpl(properties.getTenantMode());
    }

    @Bean
    public FileClient fileClient(){
        return new MasterFileClient(properties);
    }

    @Bean(initMethod = "init")
    public S3OssTemplate s3OssTemplate(OssConfigFactory factory, OssRule ossRule){
        return new S3OssTemplate(factory, ossRule);
    }

    @Bean(initMethod = "init")
    public DbOssTemplate dbOssTemplate(OssConfigFactory factory, OssRule ossRule, OssFileApi ossFileApi){
        return new DbOssTemplate(factory, ossRule, ossFileApi);
    }

    @Bean(initMethod = "init")
    public LocalOssTemplate localOssTemplate(OssConfigFactory factory, OssRule ossRule){
        return new LocalOssTemplate(factory, ossRule);
    }

    @Bean
    public OssRecordListener ossRecordListener(OssRecordApi ossRecordApi){
        return new OssRecordListener(ossRecordApi);
    }
}
